package logic

import (
	"context"
	"gitee.com/yumo01/weikang-srv/internal/svc"
	"gitee.com/yumo01/weikang-srv/weikang"
	"github.com/15733012783/weikang/model/mysql"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *weikang.User) (*weikang.Response, error) {

	var u = mysql.User{
		Username: in.Name,
		Password: in.Password,
		Phone:    in.Phone,
	}
	_, err := mysql.InItMysql(func(db *gorm.DB) (interface{}, error) {
		var count int64
		err := db.Table("users").Where("username = ?", in.Name).Count(&count).Error
		if err != nil {
			return nil, status.Errorf(codes.FailedPrecondition, "用户列表查询失败"+err.Error())
		}
		if count > 0 {
			return nil, status.Errorf(codes.AlreadyExists, "用户已存在")
		}

		err = db.Table("users").Create(&u).Error
		if err != nil {
			return nil, status.Errorf(codes.FailedPrecondition, "注册用户失败"+err.Error())
		}
		return nil, nil
	})
	return nil, err
}
